package com.blink.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * <Description> 本工程创建的zookeeper都通过该辅助类创建</Description>
 * <ClassName> ZooKeeperCreator</ClassName>
 *
 * @Author liuxianzhao
 * @Date 2018年01月12日 15:27
 */
public class ZooKeeperCreator {

    public static ZooKeeper getZk(String zkName) {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper("127.0.0.1:2181/zk-learn", 10000,
                    new ZookeeperWatcher(zkName, countDownLatch));
            countDownLatch.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return zk;
    }


    /**
     * 提前创建zk-learn节点
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    private static void createParent() throws KeeperException, InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper("127.0.0.1:2181", 10000,
                    new ZookeeperWatcher("", countDownLatch));
            countDownLatch.await();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        zk.create("/zk-learn", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        zk.close();
    }

    public static void main(String[] args) {
        try {
            ZooKeeperCreator.createParent();
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
